package app.itgungnir.compose.wan.business.my_collection

import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.InsertLink
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Title
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.text.HtmlCompat
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import app.itgungnir.compose.wan.R
import app.itgungnir.compose.wan.theme.WanComposePreviewTheme
import app.itgungnir.compose.wan.widgets.*
import coil.compose.rememberImagePainter
import coil.transform.RoundedCornersTransformation

@Composable
fun MyCollectionItem(
    navController: NavController = rememberNavController(),
    item: MyCollection?,
    editCallback: (MyCollection) -> Unit,
    deleteCallback: (MyCollection) -> Unit
) {
    item ?: return
    WanSwipeMenuCard(
        modifier = Modifier.padding(top = 10.dp),
        onClick = { /* TODO */ },
        menuItems = listOf(
            WanSwipeMenuItem(icon = Icons.Filled.Delete, title = "删除", backgroundColor = MaterialTheme.colors.error) {
                deleteCallback.invoke(item)
            },
        )
    ) {
        item.envelopePic?.takeIf { it.isNotEmpty() }?.let { url ->
            Image(
                modifier = Modifier
                    .padding(end = 10.dp)
                    .width(50.dp)
                    .height(75.dp),
                painter = rememberImagePainter(
                    data = url,
                    builder = {
                        placeholder(R.drawable.svg_image_placeholder)
                        error(R.drawable.svg_image_error)
                        transformations(RoundedCornersTransformation(15F))
                    }
                ),
                contentDescription = ""
            )
        }
        Column(modifier = Modifier.weight(1F)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                item.chapterName?.takeIf { it.isNotEmpty() }?.let { chapterName ->
                    WanTagButton(modifier = Modifier.padding(bottom = 2.dp, end = 5.dp), text = chapterName)
                }
                WanTitle(content = HtmlCompat.fromHtml("${item.title}", HtmlCompat.FROM_HTML_MODE_COMPACT).toString())
            }
            Spacer(modifier = Modifier.height(3.dp))
            item.desc?.takeIf { it.isNotEmpty() }?.let {
                WanDescription(
                    modifier = Modifier.padding(bottom = 3.dp),
                    content = HtmlCompat.fromHtml("${item.desc}", HtmlCompat.FROM_HTML_MODE_COMPACT).toString()
                )
            }
            Row(verticalAlignment = Alignment.CenterVertically) {
                Column(modifier = Modifier.weight(1F)) {
                    WanInfo(content = item.author, prefix = "作者：")
                    WanInfo(content = item.niceDate)
                }
                if (item.chapterId <= 0) {
                    WanIconButton(
                        modifier = Modifier.size(20.dp),
                        icon = Icons.Outlined.Edit,
                        color = MaterialTheme.colors.onBackground
                    ) {
                        editCallback.invoke(item)
                    }
                }
            }
        }
        Spacer(modifier = Modifier.width(5.dp))
    }
}

@Composable
fun ColumnScope.CollectionEditDialogUI(
    origin: MyCollection? = null,
    confirmCallback: (String, String, String) -> Unit,
    loadingState: State<Boolean> = mutableStateOf(false),
    errorState: State<Throwable?>? = null
) {
    val focusManager = LocalFocusManager.current
    val titleValue = remember { mutableStateOf(TextFieldValue(text = origin?.title ?: "")) }
    val linkValue = remember { mutableStateOf(TextFieldValue(text = origin?.link ?: "")) }
    val authorValue = remember { mutableStateOf(TextFieldValue(text = origin?.author ?: "")) }
    WanTitle(
        modifier = Modifier.align(Alignment.CenterHorizontally),
        content = if (origin == null) "新增文章信息" else "修改文章信息"
    )
    Spacer(modifier = Modifier.height(5.dp))
    WanOutlinedInput(state = titleValue, label = "标题", icon = Icons.Filled.Title, loadingState = loadingState)
    Spacer(modifier = Modifier.height(5.dp))
    WanOutlinedInput(state = linkValue, label = "链接", icon = Icons.Filled.InsertLink, loadingState = loadingState)
    Spacer(modifier = Modifier.height(5.dp))
    WanOutlinedInput(state = authorValue, label = "作者", icon = Icons.Filled.Person, loadingState = loadingState)
    Spacer(modifier = Modifier.height(15.dp))
    WanButton(
        modifier = Modifier.fillMaxWidth(),
        text = if (origin == null) "确认新增" else "确认修改",
        loadingState = loadingState
    ) {
        focusManager.clearFocus()
        confirmCallback.invoke(titleValue.value.text, linkValue.value.text, authorValue.value.text)
    }
    WanError(modifier = Modifier.padding(top = 5.dp), contentState = errorState)
}

@Preview(name = "MyCollectionItem light mode", showBackground = false)
@Preview(name = "MyCollectionItem dark mode", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = false)
@Composable
private fun MyCollectionItemPreview() {
    WanComposePreviewTheme {
        val item = MyCollection(
            id = 0L,
            originId = 0L,
            title = "标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题",
            desc = "内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容",
            author = "作者作者作者",
            chapterId = 0,
            chapterName = "分类分类分类",
            niceDate = "2021-11-06 09:34:58",
            envelopePic = "https://www.wanandroid.com/resources/image/pc/default_project_img.jpg",
            link = "https://www.baidu.com/"
        )
        MyCollectionItem(item = item, editCallback = {}, deleteCallback = {})
    }
}

@Preview(name = "CollectionEditDialog light mode", showBackground = false)
@Preview(name = "CollectionEditDialog dark mode", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = false)
@Composable
private fun CollectionEditDialogPreview() {
    val item = MyCollection(
        id = 0L,
        originId = 0L,
        title = "标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题标题",
        desc = "内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容",
        author = "作者作者作者",
        chapterId = 0,
        chapterName = "分类分类分类",
        niceDate = "2021-11-06 09:34:58",
        envelopePic = "https://www.wanandroid.com/resources/image/pc/default_project_img.jpg",
        link = "https://www.baidu.com/"
    )
    WanDialogPreview {
        CollectionEditDialogUI(origin = item, confirmCallback = { _, _, _ -> })
    }
}
